package com.base.common.util;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Iterator;

import javax.imageio.ImageIO;
import javax.imageio.ImageReader;
import javax.imageio.stream.ImageInputStream;

/**
 * 图片处理
 * 
 * @author yanjiaqiang
 * 
 */
public class ImageUtils {

	/**
	 * 判断是否为能被Java识别的图片
	 * 
	 * @param filepath
	 * @return
	 */
	public static boolean isImage(String filepath) {
		return isImage(new File(filepath));
	}

	public static boolean isImage(File file) {
		try {
			BufferedImage src = javax.imageio.ImageIO.read(file);
			return src != null;
		} catch (IOException e) {
			e.printStackTrace();
		}
		return false;
	}

	public static String getFormatName(String filePath) {
		return getFormatName(new File(filePath));
	}

	public static String getFormatName(File file) {
		if (file.exists()) {
			return getFormatName0(file);
		}
		return null;
	}

	private static String getFormatName0(Object o) {

		ImageInputStream iis = null;
		try {
			iis = ImageIO.createImageInputStream(o);
			Iterator<ImageReader> iter = ImageIO.getImageReaders(iis);
			if (!iter.hasNext()) {
				return null;
			}
			ImageReader reader = iter.next();
			return reader.getFormatName();
		} catch (IOException e) {
			throw new RuntimeException(e);
		} finally {
			try {
				iis.close();
			} catch (IOException e) {
				throw new RuntimeException(e);
			}
		}
	}
}
